package com.xc.smart.security.service;

import com.xc.smart.entity.LoginUser;
import com.xc.smart.entity.User;
import com.xc.smart.service.RoleService;
import com.xc.smart.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * 用户验证处理
 * @author mtl
 */
@Slf4j
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.selectByName(username);
        if (StringUtils.isEmpty(user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }

        return createLoginUser(user);
    }

    /**
     * 获取用户权限信息
     * @param user
     * @return
     */
    public UserDetails createLoginUser(User user) {
        Set<String> roles = roleService.selectUserRoleByUser(user.getId());
        return new LoginUser(user, roles);
    }
}
